package wiki.douzi.helpyougrow.filter;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class Filter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String requestHeaderMethod = httpServletRequest.getHeader("Access-Control-Request-Method");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        if (requestHeaderMethod != null && "OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) {
            httpServletResponse.addHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
            httpServletResponse.addHeader("Access-Control-Max-Age", "1");
            httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            System.out.println("跨域成功");
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
